package com.learncloud.security.extension.mobile;

import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author lbx
 * @version 1.0.0
 * @description 短信验证码认证授权提供者
 * @date 2021/10/29 13:39
 **/
@Data
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = (SmsCodeAuthenticationToken) authentication;
        String mobile = (String) smsCodeAuthenticationToken.getPrincipal();
        String code = (String) smsCodeAuthenticationToken.getCredentials();
        //进行短信验证码验证

        //区分用户类别

        UserDetails  userDetails = userDetailsService.loadUserByUsername(mobile);

        SmsCodeAuthenticationToken authenticationToken = new SmsCodeAuthenticationToken(userDetails,userDetails.getAuthorities());
        authenticationToken.setDetails(smsCodeAuthenticationToken.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
